package com.example.xiaomaotv;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.xiaomaotv.adapter.MineAdapter;
import com.example.xiaomaotv.entity.Mine;

import java.util.ArrayList;
import java.util.List;

public class MineFragment extends Fragment {
    private ImageView exit_btn;
    private SharedPreferences sp;
    private ImageView title;
    private TextView username,reserve,download,playlist,favorite;
    private View mineView;
    private MySQL helper;
    private SQLiteDatabase database;
    private List<Mine> mineData = new ArrayList<>();
    private ListView mineList ;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mineView = inflater.inflate(R.layout.mine_fragment, null);
        // 初始化 SharedPreferences
        sp = requireContext().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        // 初始化数据库
        helper = new MySQL(getActivity(), "XiaoMaoTv", null, 1);
        database = helper.getWritableDatabase();
        // 初始化控件
        initView();
        //列表
        initDate();
        // 设置用户名
        setUsername();
        // 设置头像
        loadAvatarFromSP();
        setMineList();
        //点击事件
        clickTop();

        return mineView;
    }
    public void initView(){
        username = mineView.findViewById(R.id.mine_username);
        title = mineView.findViewById(R.id.mine_title);
        exit_btn = mineView.findViewById(R.id.BTN_EXIT);
        mineList = mineView.findViewById(R.id.mine_list);
        reserve = mineView.findViewById(R.id.tv_reserve);
        download = mineView.findViewById(R.id.tv_download);
        playlist = mineView.findViewById(R.id.tv_playlist);
        favorite = mineView.findViewById(R.id.tv_favorite);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadAvatarFromSP();
    }
    // 从 SharedPreferences 加载头像并设置
    private void loadAvatarFromSP() {
        String avatarRes = sp.getString("title", ""); // 获取保存的头像标识
        try {
            int resId = getResources().getIdentifier(avatarRes, "drawable", requireContext().getPackageName());
            if (resId != 0) {
                Drawable drawable = getResources().getDrawable(resId);
                title.setImageDrawable(drawable);
                Toast.makeText(requireContext(), "头像更换成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireContext(), "头像资源不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            title.setImageResource(R.drawable.title); // 兜底默认头像
        }
    }
    private void showAvatarDialog() {
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.login_title_dialog, null);
        EditText etTitle = dialogView.findViewById(R.id.et_title);

        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("更换头像")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String newTitle = etTitle.getText().toString().trim();
                    if (!newTitle.isEmpty()) {
                        // 保存到 SharedPreferences
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("title", newTitle);
                        editor.apply();
                        // 立即更新当前头像
                        loadAvatarFromSP();
                    }else {
                        Toast.makeText(requireContext(), "请输入头像标识", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null);
        builder.create().show();
    }
    //显示修改用户名对话框
    private void showUsernameDialog() {
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.username_modify_dialog, null);
        EditText etUsername = dialogView.findViewById(R.id.et_username);
        // 设置当前用户名作为默认值
        etUsername.setText(username.getText().toString());
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("修改用户名")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String newUsername = etUsername.getText().toString().trim();
                    if (!newUsername.isEmpty()) {
                        // 更新数据库
                        updateUsernameInDatabase(newUsername);
                        username.setText(newUsername);
                        Toast.makeText(requireContext(), "用户名修改成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(requireContext(), "用户名不能为空", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null);
        builder.create().show();
    }
    //更新数据库中的用户名
    private void updateUsernameInDatabase(String newUsername) {
        String savedAccount = sp.getString("account", "");
        if (!savedAccount.isEmpty()) {
            try {
                String sql = "UPDATE user SET username = ? WHERE account = ?";
                database.execSQL(sql, new String[]{newUsername, savedAccount});
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(requireContext(), "修改失败，请重试", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void setUsername() {
        String savedAccount = sp.getString("account", "");
        Cursor cursor = database.query(
                "user",
                null,
                "account=?",
                new String[]{savedAccount},
                null,
                null,
                null
        );
        try {
            if (cursor.moveToFirst()) {
                String usernameSave = cursor.getString(
                        cursor.getColumnIndex("username")
                );
                username.setText(usernameSave);
            }
        } catch (Exception e) {
            e.printStackTrace();
            username.setText("未知用户"); // 兜底，避免空指针
        } finally {
            cursor.close();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (database != null && database.isOpen()) {
            database.close();
        }
    }
    public void initDate(){
        if (mineData.isEmpty()){
            Mine M1 = new Mine(R.drawable.mine_guankanlishi,"观看历史", R.drawable.mine_enter);
            Mine M2 = new Mine(R.drawable.mine_jinbi,"我的金币", R.drawable.mine_enter);
            Mine M3 = new Mine(R.drawable.mine_zijin,"我的资产", R.drawable.mine_enter);
            Mine M4 = new Mine(R.drawable.mine_wenjuan,"问卷调查", R.drawable.mine_enter);
            Mine M5 = new Mine(R.drawable.mine_zaixiankefu,"在线客服", R.drawable.mine_enter);
            Mine M6 = new Mine(R.drawable.mine_gengduo,"更多设置", R.drawable.mine_enter);
            Mine M7 = new Mine(R.drawable.mine_shezhi,"设置中心", R.drawable.mine_enter);
            mineData.add(M1);
            mineData.add(M2);
            mineData.add(M3);
            mineData.add(M4);
            mineData.add(M5);
            mineData.add(M6);
            mineData.add(M7);
        }
    }
    public void setMineList(){
        MineAdapter mineAdapter = new MineAdapter(getActivity(),R.layout.item_mine,mineData);
        mineList.setAdapter(mineAdapter);
        mineList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取点击的列表项数据
                Mine selectedItem = mineData.get(position);
                // 创建Intent跳转到MainActivity5
                Intent intent = new Intent(getActivity(), MainActivity5.class);
                // 传递数据
                intent.putExtra("TEXT", selectedItem.getText());
                // 启动Activity
                startActivity(intent);
            }
        });
    }
    private void clickTop(){
        reserve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentTop("预约");
            }
        });
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentTop("下载");
            }
        });
        playlist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentTop("片单");
            }
        });
        favorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentTop("收藏");
            }
        });
        // 头像点击事件
        title.setOnClickListener(v -> showAvatarDialog());
        // 用户名点击事件
        username.setOnClickListener(v -> showUsernameDialog());
        // 退出按钮事件
        exit_btn.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        });
    }
    public void intentTop(String text){
        Intent intent = new Intent(getActivity(), MainActivity5.class);
        intent.putExtra("TEXT",text);
        startActivity(intent);
    }

}